<template>
  <div ref="Panel" class="charts" style="width: 100%; height: 400px"></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { useI18n } from 'vue-i18n';

const i18n = useI18n();
const panelChart = shallowRef();
const Panel = ref();
const timer = ref();
const props = defineProps<{
  compName: string | number;
  currentData: {
    usage: string;
    capacity?: string;
    capacityUnit?: string;
    compName: string;
    unit?: string;
    free?: string;
    freeUnit?: string;
  };
}>();

onMounted(() => {
  let titleText = props.compName;

  if ('capacity' in props.currentData) {
    if (props.currentData.compName === 'Disk')
      titleText =
        props.compName +
        '(' +
        i18n.t('pagePerformanceMonitor.totalCapacity') +
        props.currentData.capacity +
        props.currentData.capacityUnit +
        ')';
    else if (props.currentData.compName === 'Memory')
      titleText =
        props.compName +
        '(' +
        i18n.t('pagePerformanceMonitor.totalCapacity') +
        props.currentData.capacity +
        props.currentData.unit +
        ')';
  }
  panelChart.value = echarts.init(Panel.value);
  timer.value = setInterval(() => {
    var usage = parseInt(props.currentData.usage);

    let title;
    if (props.currentData.compName === 'Disk')
      title = [
        {
          text: titleText,
          left: 'center',
        },
        {
          text:
            i18n.t('pagePerformanceMonitor.free') +
            ':' +
            props.currentData.free +
            props.currentData.freeUnit,
          top: '300',
          left: 'center',
        },
      ];
    else
      title = [
        {
          text: titleText,
          left: 'center',
        },
      ];

    const options = {
      title,
      tooltip: {
        formatter: '{a}: {c}%',
      },
      series: [
        {
          name: i18n.t('pagePerformanceMonitor.usage'),
          type: 'gauge',
          detail: {
            formatter: '{value}%',
            textStyle: {
              fontSize: 18,
            },
          },
          data: [{ value: usage }],
        },
      ],
    };

    panelChart.value.setOption(options, {
      notMerge: false,
      lazyUpdate: true,
      silent: false,
    });
    panelChart.value.resize();
  }, 1000);
});

onBeforeUnmount(() => clearInterval(timer.value));
</script>
